import win32gui
import time
import pyautogui
import math
import random
from pynput import keyboard
import cv2


class t1t:
    def __init__(self):
        # 获取小程序
        self.hwnd_target = win32gui.FindWindow(None, '跳一跳')
        self.peple_center = 0
        self.new_center = 0
        self.min_loc = 0
    #     调整以下参数，纠正程序
        self.gauss_param = (19,19) #高斯模糊参数
        self.jump_time = 2.1     #鼠标按压时间参数

    # 获取最新的游戏界面截图
    def jump_img(self):
        # 放到前台
        try:
            win32gui.SetForegroundWindow(self.hwnd_target)
        except:
            print('未找到程序')
            return False
        # 获取小程序坐标
        left, top, right, bot = win32gui.GetWindowRect(self.hwnd_target)
        pyautogui.moveTo(left + 200,top+200,duration=0.1)
        #  截图
        img = pyautogui.screenshot(region=(left, top, 603, 1117))  # 默认是全屏，可是输入截屏大小
        # 保存前一张图片，调试使用
        old_img = open("img.jpg", "rb")
        data = old_img.read()
        old_img.close()
        new_img = open("img_pre.jpg", "wb")
        new_img.write(data)
        new_img.close()
        # 保存图像
        img.save("img.jpg")

    # 展示匹配结果
    def ShowImage(self,name, image):
        cv2.imshow(name, image)
        cv2.waitKey(0)  # 等待时间，0表示任意键退出
        cv2.destroyAllWindows()

    # 匹配跳一跳小人的位置.->模板匹配
    def match_peple_postion(self):
        # 原图和模板图取灰度图
        image = cv2.imread('img.jpg', 0)
        template = cv2.imread('me.png', 0)
        # 获取模板图的宽高
        h, w = template.shape[:2]
        # 匹配到的最终结果
        res_img = image.copy()
        # 获取最相似的像素点
        res = cv2.matchTemplate(image, template, cv2.TM_SQDIFF)
        # 通过相似点，获得其在原图像中的最小值，最大值，和位置最小值，最大值。
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        self.min_loc = min_loc
        # 标记人物中心点
        self.peple_center = (min_loc[0] +25 , min_loc[1]+110)

        # cv2.circle(res_img,self.peple_center, 5, (255, 0, 0), -1)
        # 标记人物的框
        # cv2.rectangle(res_img, min_loc, (min_loc[0] + w, min_loc[1] + h), 255, 2)
        # self.ShowImage('temp', res_img)

    # 查找最新的落脚点的位置->边缘检测
    def find_next_positon(self):
        img = cv2.imread("img.jpg")
        img_blur = cv2.GaussianBlur(img, self.gauss_param, 0)  # 高斯模糊
        canny_img = cv2.Canny(img_blur, 1, 10)  # 边缘检测
        # 消除人物，避免干扰落脚点（离得近的时候会干扰）
        for y in range(self.min_loc[1], self.min_loc[1]+220 ):
            for x in range(self.min_loc[0], self.min_loc[0]+50):
                canny_img[y][x] = 0
        # 裁切落脚点有用的哪一部分
        height, width = canny_img.shape
        crop_img = canny_img[300:int(height / 2), 0:width]

        # 找落脚点的中心点
        crop_h, crop_w = crop_img.shape
        center_x, center_y = 0, 0
        max_x = 0
        for y in range(crop_h):
            for x in range(crop_w):
                if crop_img[y, x] == 255:
                    if center_x == 0:
                        center_x = x
                    if x > max_x:
                        center_y = y
                        max_x = x

        self.new_center = (center_x, center_y+300)
        # cv2.circle(crop_img,self.new_center, 10, 255, -1)
        # self.ShowImage('sss',crop_img)

    def action(self):
        # res_img = cv2.imread("img.jpg")
        # cv2.line(res_img, self.peple_center, self.new_center, 255)
        # self.ShowImage('最终结果', res_img)
        # exit()
    #         计算两点之间的距离
        a = self.peple_center[0] - self.new_center[0]
        b = self.peple_center[1] - self.new_center[1]
        distance = math.sqrt(a * a + b * b)
        print(distance)
    # 操作鼠标
        pyautogui.mouseDown()  # 按下鼠标按键（左键）
        if distance < 118: #距离短，单独处理
            time.sleep(distance * (self.jump_time - 0.4) / 1000)
        elif distance > 350: #距离长，单独处理
            time.sleep(distance * (self.jump_time + 0.6) / 1000)
        else:
            time.sleep(distance * self.jump_time / 1000)

        pyautogui.mouseUp()  # 释放鼠标按键（左键）

    def on_press(self,key):
        global message
        message = str(key).replace(f'{chr(39)}', '')


if __name__ == "__main__":
    tt = t1t()
    message = ''
    tag = True
    listener = keyboard.Listener(on_press=tt.on_press)
    listener.start()

    while tag:

        if message == 'z':
            # print('持续暂停中。。。')
            time.sleep(1)
        if message == 'Key.space':
            # print('持续干活中。。。')
            # 截图最新的画面
            find=tt.jump_img()
            if find == False:
                message = 'no'
                continue
            # 找到小人中心点
            tt.match_peple_postion()
            # 找到下一个落脚点的中心点
            tt.find_next_positon()
            # 计算距离，执行操作
            tt.action() 
            # 间隔设置随机数不能太短，会受到落地效果影响
            time.sleep(random.randint(2, 5))
            # time.sleep(1)
        if message == 'no':
           # print('请打开小程序')
           time.sleep(0.5)
        if message == 'Key.esc':
            # print('退出程序')
            listener.stop()
            tag = False










